package com.geeguo.ebuilder.client.base.redis.utils;

import com.geeguo.ebuilder.client.base.tenant.model.DataContext;
import com.geeguo.ebuilder.client.base.tenant.utils.DataContextHolder;
import com.geeguo.ebuilder.core.common.exception.ApplicationException;
import com.geeguo.ebuilder.core.redis.utils.AbstractCacheKeyFactory;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

@Component
public class CacheKeyFactory extends AbstractCacheKeyFactory {

    public static final CacheKeyFactory INSTANCE = new CacheKeyFactory();

    protected String getApplicationName() {
        return "CLIENT";
    }

    private String genTK(String... keys) {
        DataContext dataContext = DataContextHolder.getDataContext();
        return genTK(dataContext, keys);
    }

    private String genTK(DataContext dataContext, String... keys) {
        if (dataContext == null || StringUtils.isBlank(dataContext.getTenantCode())) {
            throw new ApplicationException("未发现租户编码。");
        }
        return genK(ArrayUtils.insert(0, keys, dataContext.getTenantCode()));
    }

    // 密码重试次数
    public String getPasswordRetryCount(String userId, DataContext dataContext) {
        return genTK(dataContext, "PASSWORD_RETRY_COUNT", userId);
    }

    // 用户web端模块列表
    public String getUserWebModuleList(String userId, DataContext dataContext) {
        return genTK(dataContext, "USER_WEB_MODULE_LIST", userId);
    }

    // 用户
    public String getUser(String id, DataContext dataContext) {
        return genTK(dataContext, "USER", id);
    }

    // 组织机构
    public String getOrganization(String id, DataContext dataContext) {
        return genTK(dataContext, "ORGANIZATION", id);
    }
}